package com.flyu.myThread.Syn;

/*
模拟不安全的抢票
 */
public class UnsafeTickets {
    public static void main(String[] args) {
        BuyTickets buyTickets = new BuyTickets();

        new Thread(buyTickets, "苦逼的我").start();
        new Thread(buyTickets, "牛逼的你").start();
        new Thread(buyTickets, "可恶的黄牛").start();
    }
}

class BuyTickets implements Runnable{

    private int nums = 10;  // 定义10张票
    boolean flag = true;    // 外部停止方式

    @Override
    public void run() {
        // 买票
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void buy() throws InterruptedException {
        // 判断是否有票
        if (nums < 0){
            flag = false;
            return;
        }
        // 模拟延时
        Thread.sleep(100);
        // 买票
        System.out.println(Thread.currentThread().getName()+"拿到"+nums--);
    }
}


